﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Configuration;
using Zhuang.WinForm.ControlLibrary.Components.Grid;
using Zhuang.Utility.WinForm.Grid;


namespace Zhuang.WinForm.ControlLibrary.Components.Forms
{
    public partial class SearchSelect : Form
    {
        public class Setting {


            private bool isSingle = false;
            /// <summary>
            /// 是否是单选
            /// </summary>
            public bool IsSingle
            {
                get { return isSingle; }
                set { isSingle = value; }
            }

            private bool isAutoSelectWhenSingle = true;
            /// <summary>
            /// 是否在单选模式下如果只有一条记录就自动选择
            /// </summary>
            public bool IsAutoSelectWhenSingle
            {
                get { return isAutoSelectWhenSingle; }
                set { isAutoSelectWhenSingle = value; }
            }

            bool isShowMx = false;
            /// <summary>
            /// 是否显示明细
            /// </summary>
            public bool IsShowMx
            {
                get { return isShowMx; }
                set { isShowMx = value; }
            }

            

            bool hasMx = false;
            /// <summary>
            /// 是否有明细数据
            /// </summary>
            public bool HasMx
            {
                get { return hasMx; }
                set { hasMx = value; }
            }
            
            string idName = "id";
            /// <summary>
            /// 主键字段名字
            /// </summary>
            public string IdName
            {
                get { return idName; }
                set { idName = value; }
            }


            private bool isDefaultUnvisibleColumns = false;
            /// <summary>
            /// 是否默认所有列都隐藏
            /// </summary>
            public bool IsDefaultUnvisibleColumns
            {
                get { return isDefaultUnvisibleColumns; }
                set { isDefaultUnvisibleColumns = value; }
            }


            private Dictionary<string, int> dicFieldsWidth = new Dictionary<string, int>();
            /// <summary>
            /// 字段显示的宽度
            /// </summary>
            public Dictionary<string, int> DicFieldsWidth
            {
                get { return dicFieldsWidth; }
                set { dicFieldsWidth = value; }
            }


            private Dictionary<string, bool> dicFieldsReadOnly = new Dictionary<string, bool>();
            /// <summary>
            /// 字段是否可编缉
            /// </summary>
            public Dictionary<string, bool> DicFieldsReadOnly
            {
                get { return dicFieldsReadOnly; }
                set { dicFieldsReadOnly = value; }
            }

            private Dictionary<string, string> dicFieldsHeadText = new Dictionary<string, string>();
            /// <summary>
            /// 字段的中文显示
            /// </summary>
            public Dictionary<string, string> DicFieldsHeadText
            {
                get { return dicFieldsHeadText; }
                set { dicFieldsHeadText = value; }
            }




            private ArrayList alFitlerFields = new ArrayList();
            /// <summary>
            /// 要进行条件过滤的字段，如果没有设置则所有字段都启作用
            /// </summary>
            public ArrayList AlFitlerFiels
            {
                get { return alFitlerFields; }
                set { alFitlerFields = value; }
            }


            private ArrayList alUnvisibleFields = new ArrayList();
            /// <summary>
            /// 要进行隐藏的字段
            /// </summary>
            public ArrayList AlUnvisibleFields
            {
                get { return alUnvisibleFields; }
                set { alUnvisibleFields = value; }
            }

            
            private ArrayList alVisibleFields = new ArrayList();
            /// <summary>
            /// 要进行显示的字段
            /// </summary>
            public ArrayList AlVisibleFields
            {
                get { return alVisibleFields; }
                set { alVisibleFields = value; }
            }

           
            
        }

        Setting settings = new Setting();

        public Setting Settings
        {
            get { return settings; }
            set { settings = value; }
        }


        public delegate DataTable QueryDBHandler(string strSql);
        public event QueryDBHandler QueryDBEvent;


        int TimerTickCount = 0;


        //查询的sql语句，由构造函数传入
        private string strSql="";
        
        //过滤的条件
        private string strCondiction = "";


        int preRowIndex = 1;

        //最初查询出来未经过过滤的DataTable
        DataTable dt = new DataTable();

        public DataTable Dt
        {
            get { return dt; }
            set { dt = value; }
        }


        DataTable dtMx = new DataTable();

        public DataTable DtMx
        {
            get { return dtMx; }
            set { dtMx = value; }
        }


        //选中商品结果集
        DataTable dtResult = new DataTable();


        /// <summary>
        /// 构造函数，传查询的sql语句,内部执行查询，需设置事件处理QueryDBEvent
        /// </summary>
        /// <param name="strSql"></param>
        /// <param name="text"></param>
        public SearchSelect(string strSql)
        {
            InitializeComponent();

            this.strSql = strSql;



        }

        /// <summary>
        /// 构造函数，直接传入查询好的数据集
        /// </summary>
        /// <param name="dt"></param>
        public SearchSelect(DataTable dt)
        {
            InitializeComponent();
            this.dt = dt.Copy();
        }

        /// <summary>
        /// 
        /// </summary>
        public SearchSelect()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 返回选择的结果集
        /// </summary>
        /// <returns></returns>
        public DataTable GetResult()
        {
            return dtResult;
        }


        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            makeSelectedRowToDtResult();

            this.Close();

        }

        private void makeSelectedRowToDtResult()
        {
            dtResult = dt.Clone();

            if (settings.IsSingle == false)
            {
                foreach (DataGridViewRow dgvr in dataGridView1.Rows)
                {
                    if ((bool)dgvr.Cells["isSelected"].FormattedValue == true)
                    {
                        DataRow dr = dtResult.NewRow();
                        foreach (DataGridViewCell dgvc in dgvr.Cells)
                        {
                            if (dataGridView1.Columns[dgvc.ColumnIndex].Name != "isSelected")
                                dr[dgvc.OwningColumn.Name] = dgvc.Value;
                        }
                        dtResult.Rows.Add(dr);

                    }
                    
                }
            }
            else {
                foreach (DataGridViewRow dgvr in dataGridView1.SelectedRows)
                {
                    DataRow dr = dtResult.NewRow();
                    foreach (DataGridViewCell dgvc in dgvr.Cells)
                    {
                        if (dataGridView1.Columns[dgvc.ColumnIndex].Name != "isSelected")
                            dr[dgvc.OwningColumn.Name] = dgvc.Value;
                    }
                    dtResult.Rows.Add(dr);

                }
            }


            //dataGridView1.DataSource = dtResult;
        }

        private void SearchSelect_Load(object sender, EventArgs e)
        {
            

            if (settings.HasMx == false)
            {
                cbShowMx.Visible = false;
            }

            if (settings.IsShowMx == false)
            {
                splitContainer1.Panel2Collapsed = true;
                cbShowMx.Checked = false;
            }
            else {
                splitContainer1.Panel2Collapsed = false;
                cbShowMx.Checked = true;
            }


            if (settings.IsSingle == true)
            {
                dataGridView1.ContextMenuStrip = null;
            }




            initializeDGV();


            if (dt.Rows.Count <= 0)
            {
                MessageBox.Show("查不到记录！");
                btnCancel_Click(sender, e);
                return;
            }


            if (settings.IsAutoSelectWhenSingle == true)
            {
                if (dataGridView1.Rows.Count == 1)
                {
                    dataGridView1.Rows[0].Cells["isSelected"].Value = 1;
                    btnOK_Click(sender, e);
                }
            }

            queryDjMx();

        }
        /// <summary>
        /// 初始化DataGridView
        /// </summary>
        private void initializeDGV()
        {
            if (settings.IsSingle == true)
            {
                dataGridView1.MultiSelect = false;
                dataGridView1.Columns["isSelected"].Visible = false;
                dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            }
            else
            {
                dataGridView1.MultiSelect = true;
                dataGridView1.Columns["isSelected"].Visible = true;
                dataGridView1.SelectionMode = DataGridViewSelectionMode.CellSelect;
            }


            DGVHelper.ShowRowNumber(dataGridView1);
            if (settings.HasMx == true)
            {
                DGVHelper.ShowRowNumber(dataGridView2);
            }

            //App_Code.DGVHandler dgvHandler = new Ka.App_Code.DGVHandler(dataGridView1);

            //如果数据集来有缓存数据则直接在缓存里取，否则去服务查数据
            if (dt.Rows.Count > 0)
            {
                
            }
            else
            {

                dt = QueryDBEvent(strSql);
                //dt = SqlHelper.Query(strSql).Tables[0] ;
                //dt = web.svr_GetSp(strSql);
                //dtFieldsInfo = web.svr_GetDataTable(TableFieldHandler.getFieldsForSql(dt));
                
            }
            
            dataGridView1.DataSource = filterDateSet(dt,strCondiction,settings.AlFitlerFiels);

            //TableFieldHandler.setDgvFieldsFromDt(dataGridView1, dtFieldsInfo);

            ///设置默认所有列都隐藏
            if (settings.IsDefaultUnvisibleColumns == true)
            {
                foreach (DataGridViewColumn dgvc in dataGridView1.Columns)
                {
                    dgvc.Visible = false;
                }
            }

            //处理隐藏字段
            if (settings.AlUnvisibleFields.Count > 0)
            {
                foreach (string filed in settings.AlUnvisibleFields)
                {
                    foreach (DataGridViewColumn dgvc in dataGridView1.Columns)
                    {
                        if (filed == dgvc.Name)
                        {
                            dgvc.Visible = false;
                        }
                    }

                }
            }

            //处理显示字段
            if (settings.AlVisibleFields.Count > 0)
            {
                foreach (string filed in settings.AlVisibleFields)
                {
                    foreach (DataGridViewColumn dgvc in dataGridView1.Columns)
                    {
                        if (filed == dgvc.Name)
                        {
                            dgvc.Visible = true;
                        }
                    }
                }
            }

            foreach(var item in  settings.DicFieldsWidth)
            {
                dataGridView1.Columns[item.Key].Width = item.Value;
            }

            foreach (DataGridViewColumn dgvc in dataGridView1.Columns)
            {
                dgvc.ReadOnly = true;
            }

            foreach (var item in settings.DicFieldsReadOnly)
            {
                dataGridView1.Columns[item.Key].ReadOnly = item.Value;
            }

            foreach (var item in settings.DicFieldsHeadText)
            {
                dataGridView1.Columns[item.Key].HeaderText = item.Value;
            }


        }

        public void setText(string text)
        {
            this.Text = text;
        }

 


        public void setFilterFields()
        { 
            
        }

        private void tbCondiction_KeyUp(object sender, KeyEventArgs e)
        {

            TimerTickCount = 0;
            timer1.Start();            
            
        }

        private void filterDgv()
        {
            strCondiction = tbCondiction.Text.Trim();

            dataGridView1.DataSource = filterDateSet(dt, strCondiction, settings.AlFitlerFiels);
        }

        /// <summary>
        /// 过滤数据集，参数：1、数据集；2、过滤的条件；3、过滤的字段。
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static DataTable filterDateSet(DataTable dt,string strCondiction, ArrayList alFitlerFields)
        {

            DataTable fdt = dt.Clone();


            if (strCondiction.Trim() == "")
            {
                return dt;
            }

            string strSelect = "";


            if (alFitlerFields.Count <= 0)
            {
                foreach (DataColumn column in dt.Columns)
                {
                    alFitlerFields.Add(column.ColumnName);
                }
            }

            foreach (string field in alFitlerFields)
            {
                strSelect = strSelect + field + " like '%" + strCondiction.Trim() + "%' or ";
            }

            if (strSelect.Length > 3)
            {
                strSelect = strSelect.Substring(0, strSelect.Length - 3);
            }


            DataRow[] drs = dt.Select(strSelect);


            foreach (DataRow dr in drs)
            {
                fdt.ImportRow(dr);
            }

            return fdt;

        }

        private void SearchSelect_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)
            {
                this.Close();
            }
        }

        private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)
            {
                this.Close();
            }else if(e.KeyCode==Keys.Enter)
            {
                btnOK.Focus();

            }
        }

        private void dataGridView1_MyEvent(object sender,MyDataGridView.MyEventArgs e)
        {
            //
            if (settings.IsSingle == false)
            {
                if ((bool)dataGridView1.Rows[dataGridView1.SelectedCells[0].RowIndex].Cells["isSelected"].FormattedValue == false)
                {
                    System.Windows.Forms.DataGridViewCellStyle dgvcs = new DataGridViewCellStyle();
                    dgvcs.BackColor = System.Drawing.SystemColors.ControlDark;
                    dataGridView1.Rows[dataGridView1.SelectedCells[0].RowIndex].DefaultCellStyle = dgvcs;
                    dataGridView1.Rows[dataGridView1.SelectedCells[0].RowIndex].Cells["isSelected"].Value = 1;
                }
                else
                {
                    System.Windows.Forms.DataGridViewCellStyle dgvcs = new DataGridViewCellStyle();
                    //dgvcs.BackColor = System.Drawing.SystemColors.ControlDark;
                    dataGridView1.Rows[dataGridView1.SelectedCells[0].RowIndex].DefaultCellStyle = dgvcs;
                    dataGridView1.Rows[dataGridView1.SelectedCells[0].RowIndex].Cells["isSelected"].Value = 0;
                }

            }
            else
            {
                btnOK.Focus();
            }      
        }

        private void tbCondiction_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)
            {
                this.Close();
            }
            else if (e.KeyCode == Keys.Enter)
            {
                this.dataGridView1.Focus();
            }
        }

        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dataGridView1.Rows.Count <= 0)
                return;


            if (e.RowIndex < 0)
                return;

            if (settings.IsSingle == false)
            {
                changeSelect(sender,e);
            }
            else {
                btnOK_Click(sender, e);

            }

            

            //reLoadSelectedRows();


        }

        private void changeSelect(object sender, DataGridViewCellEventArgs e)
        {
            if ((bool)dataGridView1.Rows[e.RowIndex].Cells["isSelected"].FormattedValue == false)
            {


                System.Windows.Forms.DataGridViewCellStyle dgvcs = new DataGridViewCellStyle();
                dgvcs.BackColor = System.Drawing.SystemColors.ControlDark;
                dataGridView1.Rows[e.RowIndex].DefaultCellStyle = dgvcs;
                dataGridView1.Rows[e.RowIndex].Cells["isSelected"].Value = 1;
                
                
                //dataGridView1.Rows[e.RowIndex].Selected = true;
               
            }
            else
            {

                System.Windows.Forms.DataGridViewCellStyle dgvcs = new DataGridViewCellStyle();
                dataGridView1.Rows[e.RowIndex].DefaultCellStyle = dgvcs;
                dataGridView1.Rows[e.RowIndex].Cells["isSelected"].Value = 0;

                
                //dataGridView1.Rows[e.RowIndex].Selected = false;
                

            }
        }

        private void reLoadSelectedRows()
        {
            foreach (DataGridViewRow dgvr in dataGridView1.Rows)
            {
                if ((bool)dgvr.Cells["isSelected"].FormattedValue == true)
                    dgvr.Selected = true;

            }
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dataGridView1.Rows.Count <= 0)
                return;
            if (e.ColumnIndex < 0)
                return;


            queryDjMx();

            if (dataGridView1.Columns[e.ColumnIndex].Name != "isSelected")
                return;

            if (e.RowIndex < 0)
                return;

            if (settings.IsSingle == false)
            {
                changeSelect(sender, e);
            }
            else
            {
                btnOK_Click(sender, e);

            }


        }

        private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            //reLoadSelectedRows();
        }

        private void cbShowMx_CheckedChanged(object sender, EventArgs e)
        {
            if (cbShowMx.Checked == true)
            {
                splitContainer1.Panel2Collapsed = false;
            }
            else
            {
                splitContainer1.Panel2Collapsed = true;
            }
        }

        private void dataGridView1_KeyUp(object sender, KeyEventArgs e)
        {
            queryDjMx();
            
        }


        private void queryDjMx()
        {
            if (settings.HasMx == false)
                return;

            if (dataGridView1.Rows.Count <= 0)
                return;

            if (preRowIndex == dataGridView1.SelectedCells[0].RowIndex)
                return;


            string id = dataGridView1.Rows[dataGridView1.SelectedCells[0].RowIndex].Cells[settings.IdName].Value.ToString().Trim();

            DataTable fdt = dtMx.Clone() ;

            DataRow[] drs = dtMx.Select(settings.IdName+"='" + id + "'");


            foreach (DataRow dr in drs)
            {
                fdt.ImportRow(dr);
            }

            
            dataGridView2.DataSource = fdt;

            dataGridView2.Columns[settings.IdName].Visible = false;

            preRowIndex = dataGridView1.SelectedCells[0].RowIndex;

        }

        private void 全部选择ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow dgvr in dataGridView1.Rows)
            {
                dgvr.Cells["isSelected"].Value = 1;
            }
        }

        private void 全部不选ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow dgvr in dataGridView1.Rows)
            {
                dgvr.Cells["isSelected"].Value = 0;
            }
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            backgroundWorker1.ReportProgress(1);
            
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            switch (e.ProgressPercentage)
            { 
                case 1:
                    filterDgv();
                    break;
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {

        }

        private void timer1_Tick(object sender, EventArgs e)
        {

            if (TimerTickCount == 1)
            {
                backgroundWorker1.RunWorkerAsync();
                timer1.Stop();
            }

            TimerTickCount++;
        }

        private void SearchSelect_Shown(object sender, EventArgs e)
        {
            tbCondiction.Focus();
        }
    }
}
